package com.car.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.car.mapper.UserMapper;
import com.car.pojo.*;
import com.car.service.UserService;
import com.car.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务实现类
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public LoginInfo login(User user) {
        //1. 调用mapper接口, 根据用户名和密码查询用户信息
        User u = userMapper.selectByUsernameAndPassword(user);

        //2. 判断: 判断是否存在这个用户, 如果存在, 组装登录成功信息
        if(u != null){
            log.info("用户登录成功, 用户信息: {}", u);
            //生成JWT令牌，包含用户类型标识
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", u.getId());
            claims.put("username", u.getUsername());
            claims.put("userType", 2); // 2表示用户类型
            String jwt = JwtUtils.generateToken(claims);

            return new LoginInfo(u.getId(), u.getUsername(), u.getName(), jwt);
        }

        //3. 不存在, 返回null
        return null;
    }

    @Override
    public User getInfo(Integer id) {
        return userMapper.selectById(id);
    }
    
    @Override
    public PageResult<User> page(EmpQueryParam param) {
        //1. 设置分页参数
        PageHelper.startPage(param.getPage(), param.getPageSize());
        
        //2. 执行查询
        List<User> userList = userMapper.list(param);
        
        //3. 解析查询结果并封装
        Page<User> p = (Page<User>) userList;
        return new PageResult<>(p.getTotal(), p.getResult());
    }
    
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void save(User user) throws Exception {
        log.info("新增用户: {}", user);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
    }
    
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void update(User user) {
        log.info("修改用户: {}", user);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
    }
    
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void delete(List<Integer> ids) {
        log.info("删除用户: {}", ids);
        userMapper.deleteByIds(ids);
    }
    
    @Override
    public List<User> list() {
        return userMapper.queryAll();
    }
}

